package com.hg.chapter1.aop;

import com.hg.chapter1.aop.annotation.Action;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class MyAspect {
    //使用注解
    @Pointcut("@annotation(com.hg.chapter1.aop.annotation.Action)")
    public void annotationPointCut() {
        //不需要定义方法内容
    }

    @Before("@annotation(com.hg.chapter1.aop.annotation.Action)")
    public void beforeAnnotationPointCut(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Action annotation = method.getAnnotation(Action.class);
        System.out.println("before" + annotation.name());
    }

    @Around("annotationPointCut()")
    public void AroundAnnotationPointCut(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Action annotation = method.getAnnotation(Action.class);
        System.out.println("Around" + annotation.name());
    }

    @After("annotationPointCut()")
    public void afterAnnotationPointCut(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Action annotation = method.getAnnotation(Action.class);
        System.out.println("After"+annotation.name());
    }


    //使用方法
    @Before("execution(* com.hg.chapter1.aop.method.*.*(..))")
    public void before(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        System.out.println(method.getName());
    }

    //切点 参数（可以是注解/某个方法）
    //只是一个参数
    //可以在注解和方法中直接使用
    @Pointcut("execution(* com.hg.chapter1.aop.method.*.*(..))")
    public void annotationPointCut1() {
        System.out.println("annotationPointCut1");
    }

    //在某个切点以后
    @After("annotationPointCut1()")
    public void after(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        System.out.println("After" + method.getName());
    }
}
